<template>
  <breadCrumb :item="item" ref="breadcrumb"></breadCrumb>
  <div class="table-wrapped">
    <!-- 1.顶部 -->
    <div class="table-header">
      <!-- 1-1. 表格顶部 -->
      <div class="table-top">
        <!-- 搜索框 -->
        <div class="search-wrapped">
          <el-input v-model="adminAccount" class="w-50 m-2" size="large" placeholder="输入账号进行搜索" 
                    :prefix-icon="Search" @change='searchUserbyAccount()' clearable  @clear="clearInput()" />
        </div>
        <div class="select-wrapped">
          <el-select v-model="department" placeholder="请选择部门" clearable @change="searchForDepartment" @clear="clearOperation">
            <el-option v-for="item in departmentData" :key="item" :label="item" :value="item" />
          </el-select>
        </div>
        <div></div>
        <div></div>
        <div></div>
        <div class="button-wrapped">
					<el-button plain type="primary" @click="banUserList">筛选冻结用户</el-button>
					<el-button plain type="primary" @click="getFirstPageList">显示全部用户</el-button>
				</div>
      </div>

      <!-- 1-2. 表格内容 -->
      <div class="table-content">
        <!-- border ：为表格添加边框； @row-dblclick="openUser" ：为表格行添加双击事件 -->
        <el-table :data="tableData" style="width: 100%" border @row-dblclick="openUser" :header-cell-style="{'text-align':'center'}">
          <el-table-column type="index" width="50" align="center" :index="indexMethod" />
          <el-table-column prop="account" label="账号" align="center" />
          <el-table-column prop="name" label="姓名" width="170" align="center" />
          <el-table-column prop="sex" label="性别" width="100" align="center"/>
          <el-table-column prop="department" label="部门" width="150" align="center" />
          <el-table-column prop="email" label="邮箱" width="200" align="center" />
          <el-table-column prop="status" label="状态" width="80" align="center">
						<template #default="{row}">
							<div>
								<el-tag v-if="row.status=='1'" class="ml-2">冻结</el-tag>
								<el-tag class="ml-2" type="success" v-else>正常</el-tag>
							</div>
						</template>
					</el-table-column>
          <el-table-column prop="update_time" label="更新时间" width="170" align="center">
						<template #default="{row}">
							<div>{{row.update_time?.slice(0,10)}}</div>
						</template>
					</el-table-column>
          
          <el-table-column label="操作" width="200" align="center">
						<template #default="{row}">
							<div>
								<el-button type="primary" @click="banUserById(row.id)" :disabled='row.status==1'>冻结</el-button>
								<el-button type="success" @click="hotUserById(row.id)" :disabled='row.status==0'>解冻</el-button>
							</div>
						</template>
					</el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 2. 底部 -->
    <div class="table-footer">
      <el-pagination :page-size="1" :current-page="paginationData.currentPage" :pager-count="7"
        :total="paginationData.adminTotal" :page-count="paginationData.pageCount" @current-change="currentChange"
        layout="prev, pager, next" />
    </div>
  </div>

  <UserInfor ref="userInfor"></UserInfor>
</template>
 
<script setup lang="ts">
  import { ref, onBeforeUnmount, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import breadCrumb from '@/components/bread_crumb.vue';
  import { Search } from '@element-plus/icons-vue';
  import { bus } from "@/utils/mitt.js";
  import UserInfor from '../components/user_infor.vue';
	import { 
    searchUser, 
    searchDepartment, 
    getBanList, 
    banUser, 
    hotUser,
    getAdminListLength, 
    returnListData,
  } from '@/api/userinfor.js';
  import { getDepartment } from '@/api/setting.js';

  const breadcrumb = ref() // 面包屑
	const item = ref({
		first: '用户管理',
		second: '员工管理',
    third: '员工列表'
	})

  const indexMethod = (index:number) => { // index从0开始 
    if(paginationData.currentPage===1){
      return index+1
    }else{
      return (paginationData.currentPage-1) * 10 + (index+1)
    }
  }

  // 部门数据
  const departmentData = ref([])
	const returnDepartment = async() => {
		const res = await getDepartment()
		departmentData.value = res.data
	}
  returnDepartment()
	const adminAccount = ref<number>()
	const tableData = ref([])

  // 通过账号搜索  account identity
  const searchUserbyAccount = async () => {
    const res = await searchUser(adminAccount.value, '用户') 
    tableData.value = res.data
  }
  const clearInput = async () => {
    // 默认获取第一页的数据 returnListData(1, '用户')
    getFirstPageList() 
  }

  // 通过部门搜索
	const department = ref()
	const searchForDepartment = async () => {
		const res = await searchDepartment(department.value)
    tableData.value = res.data
	}
	const clearOperation = () => {
		getFirstPageList() 
	}

  // 筛选冻结用户
  const banUserList = async () => {
    const res = await getBanList()
    tableData.value = res.data
  }
  // 冻结用户
  const banUserById  =async (id: number) => {
    const res = await banUser(id)
    if (res.data.status == 0) {
			ElMessage({
				message: '冻结用户成功',
				type: 'success',
			})
			getFirstPageList()  // 默认获取第一页的数据
		} else {
			ElMessage.error('冻结用户失败')
		}
  } 
  // 解冻用户
  const hotUserById  = async (id: number) => {
    const res = await hotUser(id)
    if (res.data.status == 0) {
			ElMessage({
				message: '解冻用户成功',
				type: 'success',
			})
			getFirstPageList()  // 默认获取第一页的数据
		} else {
			ElMessage.error('解冻用户失败')
		}
  } 

  // 双击打开弹窗
  const userInfor = ref()
  const openUser = (row : any) => {
    bus.emit('userId', row)  
    userInfor.value.open()
  }
 
  // 孙组件编辑好后直接关闭弹窗 
  bus.on('offDialog', async (id : number) => {
		if (id) {
			const res = await returnListData(paginationData.currentPage, '用户')
      tableData.value = res.data
			getFirstPageList()
		}
  })

  // -------------------------------------------------------------------分页数据
	const paginationData = reactive({ 
		pageCount: 1, // 总页数 
		currentPage: 1, // 当前所处页数
    adminTotal : 0,  // 设置总的记录数
	})

  // 获取用户的数量
  const returnAdminListLength = async () => {
    const res = await getAdminListLength('用户')
    paginationData.adminTotal = res.data.length
    let len = Math.ceil(res.data.length / 10)
    paginationData.pageCount = len>0 ? len : 1
  }
  returnAdminListLength()

  // 默认获取第一页的数据
  const getFirstPageList = async () => {
    const res = await returnListData(1, '用户')
    tableData.value = res.data
    returnAdminListLength()
    paginationData.currentPage = paginationData.currentPage>0 ? paginationData.currentPage : 1
  }
  getFirstPageList()

  // 当当前页码发生变化时, 监听换页
  const currentChange = async (value:number) => {
    paginationData.currentPage = value
    const res = await returnListData(paginationData.currentPage, '用户')
    tableData.value = res.data
  }
</script>
 
<style lang="scss" scoped>
  .table-wrapped {
    padding: 8px;
    height: calc(100vh - 96px); // -101px
    background: #f5f5f5;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .table-header {
      .table-top {
        padding: 0 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 48px;
        background: #fff;

        .select-wrapped {
          width: 250px;
        }

      }
      .table-content {
        min-height: 10px;
        padding: 10px 20px 20px;
        background: #fff;
      }
    }

    .table-footer {
      display: flex;
      justify-content: flex-end;
    }
  }

  :deep(.el-input__inner) {
    height: 30px;  // 32
    padding: 0 15px;
  }
</style>
